package com.esp.webalbum.ftp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import com.esp.webalbum.bean.ImageBean;
import com.esp.webalbum.utils.Const;
import com.esp.webalbum.utils.Log;

import android.content.Context;



public class WebFTPClient extends FTPClient{
	
	public static String TAG = WebFTPClient.class.getCanonicalName();
	
	public boolean isDirChanged = false;
	public FileOutputStream fos = null;
	
	/**
	 * 
	 * @return Integer code 200 = Login Done ,201 = Login Fail ,401 = error for connection
	 * It first called for FTP connection 
	 * 
	 */
	
	public int getFTPConn(){
		
		int erroNo = 200;
		try
		{
			connect(InetAddress.getByName(Const.FTP_URL));
			enterLocalPassiveMode();
			boolean boolLogin  = login(Const.FTP_USER,Const.FTP_PASSWORD);
			isDirChanged = changeWorkingDirectory(Const.FTP_WEBALBUM_IMAGES);
			if(boolLogin)
			{
				//Login Success
			Log.debug(TAG,"Connecting to host " + InetAddress.getByName(Const.FTP_URL));
			Log.debug(TAG,"User " + Const.FTP_USER+ " login OK");
			
		}
		else
		{
			//No Login	
				erroNo = 201;
			}
			
		}catch (Exception e) {
			
			erroNo = 401;
			e.printStackTrace();
		}
		return erroNo;
	}
	
	
	/**
	 * 
	 * @return 0 for successfully 
	 * It's called when you complete your operation over FTP  and want to release Connection
	 */
	
	
	public int releaseConnection(){
		int errorNo = 0;
		try{
			
			if(isConnected())
			{
				Log.debug(TAG, " ReleaseConnection First Check It Connected ::" + isConnected());
				
				if(!logout())
				{
					logout();
					disconnect();
					Log.debug(TAG, " ReleaseConnection operation complete ");
				}
			}
		}
		catch (Exception e) {
			errorNo = -1;
			e.printStackTrace();
		}
		
		return errorNo;
	}
	
	public FTPFile[] getFTPFiles(){
		
		FTPFile [] ftpFiles = null;
		try
		{
			
			if(isConnected())
			{
				if(isDirChanged)
				{
					ftpFiles = listFiles();
				}
			}
			
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ftpFiles;
	}
	
	
	/**
	 * 
	 * @param client FTPClient
	 * @param fileName
	 * @return long[] each file size in specific directory
	 */
	
	
	public Long [] getFileSize(String[] strCurrentFileName){
		
		Long []lngFileSoze = null;
		List<String> assestExistList;
		ArrayList<Long> assestNewtList = new ArrayList<Long>();
		FTPFile [] ftpfiles;
		try{
				ftpfiles = listFiles();
				assestExistList= Arrays.asList(strCurrentFileName);  
				
				for(int j = 0; j < ftpfiles.length; j++)
				{
					int intFindPos = assestExistList.indexOf(ftpfiles[j].getName());
					
					if(intFindPos != -1){
						
						System.out.println("[ Available File Size ] " + ftpfiles[j].getSize());
						assestNewtList.add(ftpfiles[j].getSize());
					}
				}
				
				lngFileSoze= new Long[assestNewtList.size()];
				assestNewtList.toArray(lngFileSoze);
				
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return lngFileSoze;
		
		
	}
	
	
	public ArrayList<ImageBean> imageFileNameList(){
		
		ArrayList<ImageBean> arryListImages = null;
		FTPFile [] ftpfile;
		try
		{
			Log.verbose(TAG," callback | imageFileNameList()");
			
			if(isConnected())
			{
				
				Log.verbose(TAG, "[ Ftp Connection Done ] " + isConnected());
				
				if(isDirChanged)
				{
					Log.verbose(TAG, " [Changed Directory ] " + isDirChanged);
					ftpfile = listFiles();
					Log.verbose(TAG,"[ Available Files ] " + ftpfile.length);
					if (ftpfile.length > 0)
					{
						//TODO Image is avaiable 
						arryListImages = new ArrayList<ImageBean>();
						
						for(int j = 0; j < ftpfile.length; j++)
						{	
							if(!ftpfile[j].isDirectory())
							{
								Log.verbose(TAG,"[ Available File Name ] " + ftpfile[j].getName());
								String URL = Const.SOUND_URL;
					    		URL += ftpfile[j].getName();	
					    		Log.debug(TAG,"[ Available File PATH ] " + URL );
					    		
								ImageBean mBean = new ImageBean();
								mBean.setStrFileName(ftpfile[j].getName());
								mBean.setStrAbsPath(URL);
								arryListImages.add(mBean);
							}
						}
							
					}
					else
					{
							return  arryListImages;
					}
						
						
				}
					
			}	
			
		}catch (Exception e) {
			Log.error(TAG,e);
		}
		
		return arryListImages;
	}
	
	
	/**
	 * @param strDestination FullPath where to write file
	 * @param StrFileName  String  	ftpFileList[0].getName()
	 * @param intLength	 int getFileSize[0].length
	 */
	
	public boolean downloadFile(Context context,String strDestination,String strFileName,int intLength){
		
		 
		System.out.println("Strat Downloading .....");
	long downloaded = 0;
	boolean boolDone = false;
	InputStream is = null;
	byte[] buffer = null;
	ByteArrayOutputStream bos = null;
	try{
		
		//OpenFile for write inside
		fos = new FileOutputStream(new File(strDestination,strFileName));
		
		bos = new ByteArrayOutputStream(intLength);
		buffer = new byte[1024];
		
		if(isConnected())
		{
			is = retrieveFileStream(strFileName);
			
			int read = 0;
			
			while ((read = is.read(buffer)) != -1) {
				
				bos.write(buffer, 0, read);
				downloaded += read;
				System.out.println("Download Bytes "+ downloaded );
				}
				
				fos.write(bos.toByteArray());
				boolDone = true;
			}
			
			
			
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		 finally 
		 {
			
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
					}
				}
	
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
					}
				}
			}
	    return boolDone;
	}	

	

}	
